﻿using BasicNginx.Dtos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RabbitMQ.Client.Events;
using RabbitMQ.Client;
using System.Text;

namespace BasicNginx.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class OrderController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<OrderController> _logger;

        public OrderController(ILogger<OrderController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="orderCreateDto"></param>
        /// <returns></returns>
        [HttpPost]
        public IEnumerable<OrderCreateDto> CreateOrder(OrderCreateDto orderCreateDto)
        {
            #region 1、生产者
            {
                /*// 1、创建连接工厂
                var factory = new ConnectionFactory()
                {
                    HostName = "localhost",
                    Port = 5672,
                    Password = "guest",
                    UserName = "guest",
                    VirtualHost = "/"
                };
                using (var connection = factory.CreateConnection())
                {
                    var channel = connection.CreateModel();
                    // 2、定义队列
                    channel.QueueDeclare(queue: "order-create",
                                         durable: false,// 消息持久化(防止rabbitmq宕机导致队列丢失风险)
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    string orderJson = JsonConvert.SerializeObject(orderCreateDto);
                    // string message = "Hello World!";
                    var body = Encoding.UTF8.GetBytes(orderJson);

                    // 3、发送消息
                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = true; // 设置消息持久化
                    channel.BasicPublish(exchange: "",
                                         routingKey: "order-create",
                                         basicProperties: properties,
                                         body: body);
                }
                _logger.LogInformation("成功创建商品");*/
            }
            #endregion

            #region 2、扇形交换机
            {
                /*  var factory = new ConnectionFactory()
                  {
                      HostName = "localhost",
                      Port = 5672,
                      Password = "guest",
                      UserName = "guest",
                      VirtualHost = "/"
                  };
                  using (var connection = factory.CreateConnection())
                  {
                      var channel = connection.CreateModel();
                      // 2、定义交换机
                      channel.ExchangeDeclare(exchange: "order_fanout", type: "fanout");

                      string orderJson = JsonConvert.SerializeObject(orderCreateDto);
                      // string message = "Hello World!";
                      var body = Encoding.UTF8.GetBytes(orderJson);

                      // 3、发送消息
                      var properties = channel.CreateBasicProperties();
                      properties.Persistent = true; // 设置消息持久化
                      channel.BasicPublish(exchange: "order_fanout",
                                           routingKey: "",
                                           basicProperties: properties,
                                           body: body);
                  }
                  _logger.LogInformation("成功创建商品");*/
            }
            #endregion

            #region 3、直连交换机
            {
                /*var factory = new ConnectionFactory()
                {
                    HostName = "localhost",
                    Port = 5672,
                    Password = "guest",
                    UserName = "guest",
                    VirtualHost = "/"
                };
                using (var connection = factory.CreateConnection())
                {
                    var channel = connection.CreateModel();
                    // 2、定义交换机
                    channel.ExchangeDeclare(exchange: "order_direct", type: "direct");

                    string orderJson = JsonConvert.SerializeObject(orderCreateDto);
                    // string message = "Hello World!";
                    var body = Encoding.UTF8.GetBytes(orderJson);

                    // 3、发送消息
                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = true; // 设置消息持久化
                    channel.BasicPublish(exchange: "order_direct",
                                         routingKey: "order-sms",
                                         basicProperties: properties,
                                         body: body);
                }
                _logger.LogInformation("成功创建商品");*/
            }
            #endregion

            #region 4、主题交换机
            {
                var factory = new ConnectionFactory()
                {
                    HostName = "localhost",
                    Port = 5672,
                    Password = "guest",
                    UserName = "guest",
                    VirtualHost = "/"
                };
                using (var connection = factory.CreateConnection())
                {
                    var channel = connection.CreateModel();
                    // 2、定义交换机
                    channel.ExchangeDeclare(exchange: "sms_topic", type: "topic");

                    string orderJson = JsonConvert.SerializeObject(orderCreateDto);
                    // string message = "Hello World!";
                    var body = Encoding.UTF8.GetBytes(orderJson);

                    // 3、发送消息
                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = true; // 设置消息持久化
                    channel.BasicPublish(exchange: "sms_topic",
                                         routingKey: "sms.order",
                                         basicProperties: properties,
                                         body: body);
                }
                _logger.LogInformation("成功创建订单");
            }
            #endregion

            #region 3、RPC交换机
            {
                var factory = new ConnectionFactory()
                {
                    HostName = "localhost",
                    Port = 5672,
                    Password = "guest",
                    UserName = "guest",
                    VirtualHost = "/"
                };
                using (var connection = factory.CreateConnection())
                {
                    var channel = connection.CreateModel();
                    // 2、定义交换机
                    string replyQueueName = channel.QueueDeclare().QueueName;

                    var properties = channel.CreateBasicProperties();
                    var correlationId = Guid.NewGuid().ToString();
                    properties.CorrelationId = correlationId;
                    properties.ReplyTo = replyQueueName;

                    // 3、发送消息
                    string orderJson = JsonConvert.SerializeObject(orderCreateDto);
                    // string message = "Hello World!";
                    var body = Encoding.UTF8.GetBytes(orderJson);
                    properties.Persistent = true; // 设置消息持久化
                    channel.BasicPublish(exchange: "",
                                         routingKey: "rpc_queue",
                                         basicProperties: properties,
                                         body: body);


                    // 4、消息回调
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        Console.WriteLine($"model:{model}");
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body.ToArray());
                        if (ea.BasicProperties.CorrelationId == correlationId)
                        {
                            Console.WriteLine(" [x] 回调成功 {0}", message);
                        }

                    };
                    // 3、消费消息
                    channel.BasicQos(0, 1, false); // Qos(防止多个消费者，能力不一致，导致的系统质量问题。
                                                   // 每一次一个消费者只成功消费一个)
                    channel.BasicConsume(queue: replyQueueName,
                                         autoAck: true, // 消息确认(防止消息消费失败)
                                         consumer: consumer);


                }
                _logger.LogInformation("成功创建商品");
            }
            #endregion
            return null;
        }
    }
}
